<?php

/**
 * @Author: wuchenge
 * @Date:   2022-04-19 13:53:38
 * @Email: ligui0506@126.com
 * @Descript:
 */
namespace App\Models;

use App\Libraries\Utils;
use DB;
use Exception;

class Label extends Model
{
    protected $table    = 'labels';
    protected $guarded  = ['id', 'created_at', 'updated_at'];
    protected $fillable = ['title', 'sort', 'status', 'img'];
    protected $hidden   = ['pivot'];

    public static function getMaxSort(): int
    {
        $max = self::max('sort');
        return $max + 1;
    }

    /**
     * 图片
     * @param [type] $value [description]
     */
    public function setImgAttribute($value)
    {
        if (!empty($value)) {
            $this->attributes['img'] = Utils::setImage($value);
        }
    }

    public function getImgAttribute($value)
    {
        if (!empty($value)) {
            $value = Utils::getImage($value);
        }
        return $value;
    }

    public function articels()
    {
        return $this->belongToMany();
    }

    /**
     * 删除标签
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function del($id): array
    {
        try {

            DB::transaction(function () use ($id) {
                // 删除
                self::where('id', $id)->delete();

                // 删除关联
                ArticleLabel::where('label_id', $id)->delete();
            });

            return ['status' => true];
        } catch (Exception $e) {
            return [
                'status'  => false,
                'message' => $e->getMessage(),
            ];
        }
    }
}
